<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Python Online Compiler</title>

		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.css">
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/theme/darcula.min.css">
		<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/python/python.min.js"></script>

		<style>
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
				font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
			}

			body {
				background-color: #1a1a1a;

				color: #ffffff;
				min-height: 100vh;
			}

			.container {
				width: 50%;

				padding: 20px;
				float: left;
			}

			.header {
				text-align: center;
				padding: 10px 0;
				border-bottom: 2px solid #333;
				margin-bottom: 10px;
			}


			.editor-container {
				flex: 2;
				background: #1e1e1e;
				border-radius: 8px;
				overflow: hidden;
				height: 350px;
				margin-bottom: 20px;
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
			}

			.output-container {
				flex: 1;
				background: #1e1e1e;
				border-radius: 8px;
				overflow: hidden;
				height: 250px;
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
			}

			.CodeMirror {
				height: calc(100% - 50px) !important;
				font-size: 14px;
			}

			.output {
				padding: 20px;
				height: calc(100% - 40px);
				overflow-y: auto;
				white-space: pre-wrap;
				color: #d4d4d4;
				font-family: 'Courier New', monospace;
				background: #1e1e1e;
			}

			#outputButton {
				background: #0e639c;
				color: white;
				border: none;
				padding: 8px 16px;
				margin-top: 7px;
				margin-right: 10px;
				float: right;
				border-radius: 3px;
				cursor: pointer;
				font-family: 'Segoe UI', sans-serif;
				transition: all 0.3s;
			}

			button:hover {
				background: #1177bb;
				transform: translateY(-1px);
			}

			.loading {
				display: none;
				color: #569cd6;
				margin-left: 15px;
				font-size: 14px;
			}

			.CodeMirror-activeline-background {
				background: #2a2d2e !important;
			}

			.CodeMirror-gutters {
				background: #252526 !important;
				border-right: 1px solid #333 !important;
			}


			#xiaozhi {
				float: left;
				/*background-color: #ffffff;*/
				width: 49%;
				height: 100%;
				margin-top: 85px;

			}

			/* 	#animation{
			float: left;
		}
	#erroOutPut{
		float: left;
		width: 60%;
		height: 400px;
		margin: 20px;
		padding: 10px;
		   overflow: auto; /* 当内容超出时显示滚动条 */

			}

			*/ .chat-container {
				width: 100%;
				max-width: 800px;
				background: rgba(30, 35, 40, 0.9);
				border-radius: 15px;
				backdrop-filter: blur(12px);
				box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
				overflow: hidden;
				border: 1px solid rgba(255, 255, 255, 0.1);
			}

			.chat-header {
				padding: 20px;
				background: linear-gradient(90deg,
						rgba(45, 50, 55, 0.9),
						rgba(35, 40, 45, 0.9));
				display: flex;
				align-items: center;
				border-bottom: 1px solid rgba(255, 255, 255, 0.1);
			}

			.chat-header i {
				font-size: 24px;
				margin-right: 15px;
				color: var(--nebula-blue);
				filter: drop-shadow(0 0 5px rgba(74, 144, 226, 0.3));
			}

			.chat-header h2 {
				color: rgba(255, 255, 255, 0.9);
				font-weight: 500;
				letter-spacing: 0.5px;
			}

			.chat-messages {
				height: 60vh;
				padding: 20px;
				overflow-y: auto;
				display: flex;
				flex-direction: column;
				gap: 15px;
			}

			/* 星空滚动条 */
			.chat-messages::-webkit-scrollbar {
				width: 8px;
			}

			.chat-messages::-webkit-scrollbar-track {
				background: rgba(255, 255, 255, 0.05);
				border-radius: 4px;
			}

			.chat-messages::-webkit-scrollbar-thumb {
				background: var(--nebula-blue);
				border-radius: 4px;
				border: 1px solid rgba(255, 255, 255, 0.1);
			}

			.message {
				max-width: 75%;
				padding: 15px 20px;
				border-radius: 15px;
				position: relative;
				animation: floatUp 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28);
				line-height: 1.5;
			}

			.received {
				background: rgba(45, 50, 55, 0.8);
				color: rgba(255, 255, 255, 0.9);
				align-self: flex-start;
				border: 1px solid rgba(255, 255, 255, 0.1);
				box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.2);

			}

			.sent {
				background: rgba(45, 50, 55, 0.8);
				color: white;
				align-self: flex-end;
				box-shadow: 2px 2px 12px rgba(74, 144, 226, 0.3);
				height: 65px;
			}

			.message-time {
				font-size: 0.75rem;
				color: rgba(255, 255, 255, 0.6);
				position: absolute;

				bottom: -2px;
				right: 15px;
				font-feature-settings: "tnum";
			}

			.chat-input {
				padding: 20px;
				background: rgba(40, 45, 50, 0.8);
				display: flex;
				gap: 12px;
				border-top: 1px solid rgba(255, 255, 255, 0.1);
			}

			input[type="text"] {
				flex: 1;
				padding: 14px 20px;
				border: none;
				border-radius: 25px;
				background: rgba(255, 255, 255, 0.08);
				color: white;
				font-size: 15px;
				transition: 0.3s;
				border: 1px solid rgba(255, 255, 255, 0.1);
			}

			input[type="text"]:focus {
				background: rgba(255, 255, 255, 0.15);
				outline: none;
				box-shadow: 0 0 10px rgba(74, 144, 226, 0.2);
			}

			button {
				padding: 14px 28px;
				border: none;
				border-radius: 25px;
				background: linear-gradient(135deg,
						var(--nebula-blue),
						#3b7fc2);
				color: white;
				font-weight: 500;
				cursor: pointer;
				transition: 0.3s;
				border: 1px solid rgba(255, 255, 255, 0.2);
			}

			button:hover {
				transform: translateY(-1px);
				box-shadow: 0 5px 15px rgba(74, 144, 226, 0.3);
			}

			@keyframes floatUp {
				from {
					opacity: 0;
					transform: translateY(20px) scale(0.95);
				}

				to {
					opacity: 1;
					transform: translateY(0) scale(1);
				}
			}
		</style>
	</head>
	<body>
		<div>
			<div class="container">
				<div class="header">
					<h1>Python Online Compiler</h1>
				</div>
				<div class="editor-container">

					<textarea id="code"></textarea>
					<button id="outputButton" onclick="runCode()">▶ 运行代码</button>
					<span class="loading" id="loading">执行中...</span>
				</div>



				<div class="output-container">
					<div class="output" id="output"></div>
				</div>
			</div>





			<div id="xiaozhi">
				<!-- 	<div id="animation"><img src="Animation .gif" alt="调整尺寸" width="200" height="150"></div>
	
	<div id="erroOutPut" style="color:black;">你好！我是小智...</div> -->
				<div class="chat-container">
					<div class="chat-header">
						<i class="fas fa-comment-dots"></i>
						<h2>智能体问答</h2>
					</div>

					<div class="chat-messages" id="chat-messages">
						<div class="message received" id="messageReceived">
							您好！我是小智，有什么可以帮您？
							<span class="message-time"></span>
						</div>

						<!--  <div class="message sent" id="messageSent">
          帮我出一个循环的题目
                <span class="message-time"></span>
            </div>-->


					</div>

					<div class="chat-input">
						<input type="text" placeholder="输入消息..." id="message-input">
						<button onclick="sendMessage()">发送</button>
					</div>
				</div>



			</div>
		</div>

		<script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script>
		<!--引入在线编辑库  -->
		<script>
			let pyodide;
			let editor;

			async function initializePyodide() {
				pyodide = await loadPyodide({
					indexURL: "https://cdn.jsdelivr.net/pyodide/v0.23.4/full/"
				});
				await pyodide.loadPackage("micropip");

				pyodide.setStdout({
					batched: (text) => {
						document.getElementById('output').textContent += text;
					}
				});
				pyodide.setStderr({
					batched: (text) => {
						document.getElementById('output').textContent += '\x1B[31mError: ' + text + '\x1B[0m';

					}
				});
			}

			function initializeEditor() {
				editor = CodeMirror.fromTextArea(document.getElementById('code'), {
					mode: 'python',
					theme: 'darcula',
					lineNumbers: true,
					indentUnit: 4,
					tabSize: 4,
					autofocus: true,
					matchBrackets: true,
					autoCloseBrackets: true,
					extraKeys: {
						"Ctrl-Enter": runCode,
						"Cmd-Enter": runCode
					},
					gutters: ["CodeMirror-linenumbers", "breakpoints"],
					styleActiveLine: true
				});

			//	editor.setValue(`import sys
				//print("Python版本:", sys.version)

			//	# 安装第三方库示例：
			//	# await pyodide.runPythonAsync('import micropip; await micropip.install("pandas")')

			//	`);
			}

			async function runCode() {
				const outputElement = document.getElementById('output');
				const loadingElement = document.getElementById('loading');
				try {
					loadingElement.style.display = 'inline';
					outputElement.textContent = '';

					const code = editor.getValue();
					await pyodide.runPythonAsync(code);
				} catch (err) {
					outputElement.textContent = '\x1B[31m' + err.toString() + '\x1B[0m';

					sendMessage()
				} finally {
					loadingElement.style.display = 'none';
				}
			}

			// 初始化
			(async function() {
				await initializePyodide();
				initializeEditor();
				document.querySelector('.CodeMirror').style.fontSize = '14px';
			})();
		</script>



		<!-- 聊天框script -->
		<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

		<script>
			const chatMessages = document.getElementById('chat-messages');
			const messageInput = document.getElementById('message-input');

			// 时间格式化
			function formatTime(date) {
				return date.toLocaleTimeString('zh-CN', {
					hour: '2-digit',
					minute: '2-digit',
					hour12: false
				});
			}

			// 初始化示例时间
			function initTimes() {
				const now = new Date();
				document.querySelectorAll('.message-time').forEach((el, index) => {
					const time = new Date(now - (5 - index) * 60000);
					el.textContent = formatTime(time);
				});
			}

			// 发送消息
			function sendMessage() {
				console.log("发送消息")
				document.getElementById('message-input').style.visibility = 'hidden';
				const codeContent = editor.getValue(); // 获取编辑器中的值			
				document.getElementById('message-input').value = codeContent
				startAnimation();

				const message = messageInput.value.trim();
				if (message) {
					const time = formatTime(new Date());

					// const messageDiv = document.createElement('div');
					//messageDiv.className = 'message sent';
					// messageDiv.innerHTML = `
					//     ${message}
					//     <span class="message-time">${time}</span>
					// `;

					// chatMessages.appendChild(messageDiv);
					// messageInput.value = '';
					// scrollToBottom();



				}

				document.getElementById('messageReceived').textContent = ''; // 清空聊天框内容

				//智能体api输入数据

				// 令牌每个月需要更换
				const personalAccessToken = 'pat_eip7rXfmZGugri1W93fsopYYyJ2qx90yy0ZtW65MhPCh0IO94CVubNJbEwLikZLO';
				const botId = '7432322306632466482';
				const conversationId = '12313';
				// 设置请求头
				const headers = new Headers();
				headers.append('Authorization', `Bearer ${personalAccessToken}`);
				headers.append('Content-Type', 'application/json');
				const editorValue = editor.getValue()
				// 构造请求体
				const requestBody = {
					conversation_id: conversationId,
					bot_id: botId,
					user: '7379877640545058855',
					query: document.getElementById('message-input').value,
					stream: false // 是否使用流式传输,必须是否，要不然输出的json格式错误
				};

				// 发送POST请求
				fetch('https://api.coze.cn/open_api/v2/chat', {
						method: 'POST',
						headers: headers,
						body: JSON.stringify(requestBody)
					})
					.then(response => response.json())
					.then(data => {
						//  console.log('响应数据:', data);

						stopAnimation() //停止动画		
						const html = marked.parse(data.messages[2].content); //markdown格式转换
						document.getElementById('messageReceived').innerHTML = html;


						document.getElementById('message-input').style.visibility = 'visible';
						document.getElementById('message-input').value = '';
					})
					.catch(error => {
						console.error('请求错误:', error);
					});



			}
			//等待动画
			function startAnimation() {
				let dotCount = 0;
				animationInterval = setInterval(() => {
					dotCount = (dotCount % 6) + 1;
					document.getElementById('messageReceived').textContent = '◆'.repeat(dotCount);
				}, 300);
			}

			function stopAnimation() {
				clearInterval(animationInterval); // 关键清除方法
				animationInterval = null; // 重置变量
			}
			// 滚动到底部
			function scrollToBottom() {
				chatMessages.scrollTop = chatMessages.scrollHeight;
			}

			// 回车发送
			messageInput.addEventListener('keypress', (e) => {
				if (e.key === 'Enter') sendMessage();
			});

			// 初始化
			document.addEventListener('DOMContentLoaded', () => {
				initTimes();
				scrollToBottom();
			});
		</script>













	</body>
</html>
